package com.yh.csx.crm.core.config;

import com.yh.csx.crm.core.common.AuthFilter;
import com.yh.csx.crm.core.common.ExceptionHandler;
import com.yh.csx.crm.core.util.DateUtils;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Date;
import java.util.List;


@Configuration
public class MvcConfig {

    @Bean
    public AuthFilter authFilter() {
        return new AuthFilter();
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(authFilter());
        bean.addUrlPatterns("/*");
        return bean;
    }

    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
                resolvers.add(new ExceptionHandler());
            }
        };
    }

    @Bean
    public DateConverter dateConverter() {
        return new DateConverter();
    }

    public static class DateConverter implements Converter<String, Date> {

        @Override
        public Date convert(String s) {
            if (s == null || (s = s.trim()).length() == 0) {
                return null;
            }
            if (s.length() == 10) {
                return DateUtils.parse(s, "yyyy-MM-dd");
            } else if (s.length() == 19) {
                return DateUtils.parse(s, "yyyy-MM-dd HH:mm:ss");
            }
            throw new IllegalArgumentException("Unsupported date format: " + s);
        }
    }
}
